<template>
  <div class="container">
    <br />
    <!-- 查询 -->
    <el-form ref="queForm" :model="hisOrderChargeQuery" inline class="demo-form-inline">
      <el-form-item label="挂号单号：">
        <el-input v-model="hisOrderChargeQuery.reg_id" placeholder="请输入挂号单号"></el-input>
      </el-form-item>
      <el-form-item label="患者姓名：">
        <el-input v-model="hisOrderChargeQuery.patient_name" placeholder="请输入患者姓名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getHisList()">
          <el-icon>
            <Search />
          </el-icon>&nbsp;查询
        </el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-table v-loading="loading" :data="lists" style="width: 100%; margin-bottom: 20px" row-key="id"
        :cell-style="{ 'text-align': 'center' }" :header-cell-style="{ 'text-align': 'center' }" default-expand-all>
        <el-table-column prop="orderId" label="订单号" width="210" />
        <el-table-column prop="regId" label="挂号单号" width="200" />
        <el-table-column prop="patientName" label="患者姓名" width="180" />
        <el-table-column prop="orderAmount" label="总金额" width="100" />
        <el-table-column prop="payType" label="支付类型" width="130">
          <template v-slot="scope">
            {{ scope.row.payType == 0 ? '现金' : '支付宝' }}
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="订单状态" width="130">
          <template v-slot="scope">
            <el-tag>{{ scope.row.orderStatus == 0 ? '未支付' : '已支付' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="payTime" label="创建时间" width="180" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button-group>
              <el-button @click="viewDetails(row)">查看信息</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <br />
    <!-- 分页 -->
    <el-pagination v-model:current-page="hisOrderChargeQuery.currentPage4"
      v-model:page-size="hisOrderChargeQuery.pageSize4" :page-sizes="[5, 10, 15]" :total="total"
      layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
    <el-drawer v-model="drawerVisible" title="订单详情" :with-header="true" :size="750">
      <div>
        <p>订单号: {{ selectedRow?.orderId }}</p>
        <el-table :data="lists02" style="width: 100%" height="250">
          <el-table-column prop="itemName" label="项目名称" width="120" />
          <el-table-column prop="itemPrice" label="项目价格" width="120" />
          <el-table-column prop="itemNum" label="项目数量" width="120" />
          <el-table-column prop="itemAmount" label="小计" width="120" />
          <el-table-column prop="itemType" label="项目类型" width="130">
            <template v-slot="scope">
              {{ scope.row.itemType == 0 ? '药品' : '检查类' }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="订单状态" width="130">
            <template v-slot="scope">
              <el-tag>
                {{ scope.row.status == 0 ? '未支付' : (scope.row.status == 2 ? '已退货' : (scope.row.status == 3 ? '已完成' :
                  '已支付')) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-drawer>
  </div>

</template>
<script lang="ts">
import { defineComponent, reactive, ref, onMounted } from 'vue';
import service from '@/utils/request';
import { Search } from '@element-plus/icons-vue';

export default defineComponent({
  name: 'PrescriptionTable',
  setup() {
    interface Order {
      id: number;
      orderId: string;
      chId: string;
      patientName: string;
      orderAmount: number;
      payType: number;
      orderStatus: number;
      payTime: string;
      hasChildren?: boolean;
      parentId?: number;
      children?: Order[];
    }

    const total = ref(0);
    const drawerVisible = ref(false);
    const selectedRow = ref<Order | null>(null);
    const lists = ref<Order[]>([]);
    const lists02 = ref<Order[]>([]);
    const loading = ref(false); // 添加 loading 状态

    const hisOrderChargeQuery = reactive({
      currentPage4: 1,
      pageSize4: 10,
      reg_id: '',
      patient_name: ''
    });

    const buildTree = (data: Order[]): Order[] => {
      const map = new Map<number, Order>();
      data.forEach(item => {
        map.set(item.id, item);
      });

      return data.filter(item => {
        const parent = map.get(item.parentId || 0);
        if (parent) {
          (parent.children || (parent.children = [])).push(item);
          return false;
        }
        return true;
      });
    };

    const handleSizeChange = (val: number) => {
      hisOrderChargeQuery.size = val;
      getHisList();
    };

    const handleCurrentChange = (val: number) => {
      hisOrderChargeQuery.current = val;
      getHisList();
    };


    const getHisList = async () => {
      try {
        loading.value = true; // 开始加载
        const res = await service.post('/api/v1/jdbc/hisOrderCharge/selectAll', hisOrderChargeQuery);
        total.value = res.total;
        lists.value = buildTree(res.list);
      } catch (error) {
        console.error('请求失败:', error);
      } finally {
        loading.value = false; // 结束加载
      }
    };

    const viewDetails = async (row: Order) => {
      console.log('Viewing details for:', row);
      try {
        const res = await service.post('/api/v1/jdbc/hisOrderCharge/selectChargeDetail02', row.orderId);
        console.log(row.orderId);
        console.log(res);
        lists02.value = res;
        console.log(lists02.value);
        selectedRow.value = row;
        drawerVisible.value = true;
      } catch (error) {
        console.error('请求失败:', error);
      }
    };

    onMounted(() => {
      getHisList();
    });

    return {
      hisOrderChargeQuery,
      lists,
      total,
      loading,
      lists02,
      drawerVisible,
      selectedRow,
      handleSizeChange,
      handleCurrentChange,
      getHisList,
      viewDetails
    };
  }
});
</script>
<style scoped>
.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.container {
  margin-left: 20px;
  /* 调整这个值以改变左边距 */
}
</style>